﻿var enemyXPositions = [];
var enemyYPositions = [];
var planeX = 0;
var planeY = 0;
var planeImage = null;
var enemyPlaneImage = null;

function setUpGame() 
{
    var gameCanvas = document.getElementById("gameCanvas");
    planeImage = new Image();
    enemyPlaneImage = new Image();
  
    planeImage.src = "img/plane.png";
    enemyPlaneImage.src = "img/enemyPlane.png";
	
	var enemyY = 0;
  
    gameCanvas.getContext("2d").clearRect(0,0,gameCanvas.width,gameCanvas.height); //Xoa het trong canvas
    gameCanvas.getContext("2d").drawImage(planeImage, Math.random() * 100, Math.random() * 100);
    gameCanvas.getContext("2d").drawImage(enemyPlaneImage, 200, 150);
    gameCanvas.addEventListener("mousemove", handleMouseEvent);
	setInterval(handleTick, 25);
}
function handleMouseEvent(mouseEvent)
{
    planeX = mouseEvent.offsetX;
	planeY = mouseEvent.offsetY;
}

function handleTick()
{
	var gameCanvas = document.getElementById("gameCanvas");
  
    gameCanvas.getContext("2d").clearRect(0,0,gameCanvas .width,gameCanvas .height); //Xoa het trong canvas
    gameCanvas.getContext("2d").drawImage(planeImage, planeX, planeY);
	
	if (Math.random() < 1/20)
	{
		enemyXPositions.push(Math.random() * 800);
		enemyYPositions.push(0);
	}
	
	var currentNumber = 0;
	while (currentNumber < enemyYPositions.length)
	{
		enemyYPositions[currentNumber] = enemyYPositions[currentNumber] + 1;
		gameCanvas.getContext("2d").drawImage(enemyPlaneImage, enemyXPositions[currentNumber], enemyYPositions[currentNumber]);		
		currentNumber = currentNumber + 1;
	}
	
	//Check collison
	currentNumber = 0;
	
	while (currentNumber < enemyYPositions.length)
	{
		if ((((planeX < enemyXPositions[currentNumber]) && (enemyXPositions[currentNumber] < planeX + planeImage.width))
			|| ((planeX < enemyXPositions[currentNumber] + enemyPlaneImage.width) && (enemyXPositions[currentNumber] + enemyPlaneImage.width < planeX + planeImage.width)))
			&& 
			(((planeY < enemyYPositions[currentNumber]) && (enemyYPositions[currentNumber] < planeY+ planeImage.height))
			|| ((planeY < enemyYPositions[currentNumber] + enemyPlaneImage.height) && (enemyYPositions[currentNumber] + enemyPlaneImage.height < planeY+ planeImage.height)))
			)
		{
			alert("Bi tan cong roi!");
		}
		
		currentNumber = currentNumber + 1;
	}
	
}